<template>
  <div class="teacherList">
    <el-form
      ref="formInlineRef"
      :inline="true"
      :model="formInline"
      class="demo-form-inline"
    >
      <el-form-item prop="title" style="width: 200px">
        <el-input
          v-model="formInline.title"
          placeholder="请输入课程名称"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="formInline.status"
          clearable
          placeholder="课程状态"
          style="width: 200px"
        >
          <el-option value="Draft" label="未发布" />
          <el-option value=" Normal" label="已发布" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-select
          v-model="formInline.subjectParentId"
          placeholder="请选择一级分类"
          style="width: 150px"
          @change="subjectLevelOneChanged"
        >
          <el-option
            v-for="item in SubjectOneList"
            :key="item.id"
            :label="item.title"
            :value="item.id"
          />
        </el-select>
        <!-- 二级分类 -->
        <el-select
          v-model="formInline.subjectId"
          placeholder="请选择二级分类"
          style="max-width: 150px"
        >
          <el-option
            v-for="subject in SubjectTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="formInline.teacherId"
          placeholder="请选择讲师"
          style="width: 200px"
        >
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" :icon="Search" @click="getList"
          >查询</el-button
        >
        <el-button :icon="Refresh" @click="resetForm(formInlineRef)"
          >清空</el-button
        >
      </el-form-item>
    </el-form>
    <el-button type="danger" :icon="CirclePlus" @click="courseAdd"
      >添加讲师</el-button
    >
    <el-button type="danger" :icon="Delete" @click="delMore"
      >批量删除</el-button
    >
    <!-- 表格组件 -->

    <el-table
      :data="tableData"
      border
      stripe
      @selection-change="handleSelection"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="序号" width="80"> </el-table-column>
      <el-table-column prop="title" label="课程名称" width="120" />
      <el-table-column prop="price" label="价格" width="100" />
      <el-table-column prop="lessonNum" label="总课时" width="100" />
      <el-table-column label="课程图片" width="300px">
        <template #default="scope">
          <div class="courseInfo">
            <img
              :src="scope.row.cover"
              alt=""
              style="width: 280px; height: 150px"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="buyCount" label="销售数" width="100" />
      <el-table-column prop="viewCount" label="浏览数" width="100" />
      <el-table-column prop="status" label="课程状态" width="120"  >
        <template #default="scope">
            <!-- 修正字符串 'Draft' 前后不应有空格 -->  
    <el-tag v-if="scope.row.status === 'Draft'" type="info">未发布</el-tag>  
    <el-tag v-if="scope.row.status === 'Normal'" type="success">已发布</el-tag>  
        </template>
        </el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间" width="160" />
      <el-table-column prop="gmtModified" label="更新时间" width="160" />
      <el-table-column label="操作" width="300">
        <template #default="scope">
          <el-button type="warning" link @click="toEditInfo(scope.row.id,1)"
            ><el-icon> <EditPen /> </el-icon>修改课程</el-button
          >
          <el-button type="warning" link @click="toEditChapter(scope.row.id)"
            ><el-icon> <EditPen /> </el-icon>修改大纲</el-button
          >
          <el-button type="danger" link @click="del(scope.row.id)"
            ><el-icon> <Delete /> </el-icon>删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <!-- 给当前组件使用中文包 -->
    <el-config-provider :locale="locale">
      <el-pagination
        v-model:current-page="currentPage4"
        v-model:page-size="pageSize4"
        :page-sizes="[10, 20, 30, 40, 50]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="getList"
        @current-change="getList"
      />
    </el-config-provider>
  </div>
</template>
  
  <script setup lang="ts">
import { ref, reactive } from "vue";
import {
  Search,
  Edit,
  Delete,
  Refresh,
  CirclePlus,
} from "@element-plus/icons-vue";
import type { Action, FormInstance } from "element-plus";
import { useRouter, useRoute } from "vue-router";
// 引入中文包
import zhCn from "element-plus/es/locale/lang/zh-cn";
// 消息提示
import { ElMessage, ElMessageBox, SCOPE } from "element-plus";
import axios from "../../assets/js/axios";
import { number } from "echarts";
import { title } from "process";

// 分页器数据
const locale = zhCn;
const router = useRouter();
const formInlineRef = ref<FormInstance>();
const currentPage4 = ref(1);
const pageSize4 = ref(4);
const small = ref(false);
const background = ref(true);
const disabled = ref(false);
const total = ref(0);
const teacherList = ref<any>([]);
const SubjectOneList = ref<any>([]);

const SubjectTwoList = ref<any>([]);
const route = useRoute();
const courseId = ref(route.params.id);
// 搜索表单数据
const formInline = reactive({
  title: "",
  status: "",
  subjectParentId: "",
  subjectId: "",
  teacherId: "",
});
// 表格数据 响应式数据
const tableData = ref([]);
const selectDate = ref<Array<any>>([]);
//表格选择事件
const handleSelection = (val: Array<any>) => {
  console.log(val);
  selectDate.value = val.map((item) => item.id);
};

// 点击清空按钮
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  // 调用表单重置方法
  formEl.resetFields();
  (formInline.subjectParentId = ""),
    (formInline.subjectId = ""),
    (formInline.status = ""),
    (formInline.teacherId = ""),
    getList();
};

// 点击删除
const del = (id: number) => {
  ElMessageBox.alert("确认删除吗？", "提示", {
    // if you want to disable its autofocus
    // autofocus: false,
    confirmButtonText: "确认",
    callback: (action: Action) => {
      console.log(action);
      if (action === "confirm") {
        axios
          .del("/serviceedu/edu-course/" + id, {})
          .then((res: any) => {
            if (res.code === 200) {
              //提示删除成功
              ElMessage({
                message: "删除数据成功",
                type: "success",
              });
              // 刷新列表
              getList();
            }
          });
      }
    },
  });
};

//点击批量删除
const delMore = () => {
  if (selectDate.value.length > 0) {
    //删除
    //弹出删除提示框
    ElMessageBox.alert("您确认删除吗？", "提示", {
      // if you want to disable its autofocus
      // autofocus: false,
      confirmButtonText: "确认",
      callback: (action: Action) => {
        console.log(action);
        if (action === "confirm") {
          axios
            .del(
              "/serviceedu/edu-teacher/delMoreTeacher?ids=" + selectDate.value,
              {}
            )
            .then((res: any) => {
              if (res.code == 200) {
                ElMessage({
                  type: "success",
                  message: "删除角色成功",
                });
                getList();
              }
            });
        }
      },
    });
  } else {
    //提示
    ElMessage({
      message: "Congrats, this is a success message.",
      type: "success",
    });
  }
};
// 分页器事件

// 点击编辑
const toEditInfo = (id: number, step: number) => {
  // 跳转课程添加页面
  router.push({ path: "/info", query: { id: id, step: step } });
};
const toEditChapter= (id: number) => {
  // 跳转课程添加页面
  router.push({ path: "/chapter/"+id});
};
// 定义分页+条件请求方法
const getList = () => {
  axios
    .get("/serviceedu/edu-course/getCourseCondition", {
      page: currentPage4.value,
      size: pageSize4.value,
      title: formInline.title,
      subjectParentId: formInline.subjectParentId,
      subjectId: formInline.subjectId,
      teacherId: formInline.teacherId,
      status: formInline.status,
    })
    .then((res: any) => {
      console.log(res);
      // 接收总条数
      total.value = res.data.total;
      // 接收列表数据
      tableData.value = res.data.list;
    });
};
// 调用用户初始化查询数据方法
getList();

const courseAdd = () => {
  router.push("/info");
};
const subjectLevelOneChanged = (value: any) => {
  console.log(value);
  // 遍历 SubjectOneList 以找到匹配的项
  for (let i = 0; i < SubjectOneList.value.length; i++) {
    if (SubjectOneList.value[i].id === value) {
      // 更新 SubjectTwoList 为找到的项的 children
      SubjectTwoList.value = SubjectOneList.value[i].children;

      // 更新 couresinfo 的 subjectId（注意这里没有逗号）
      couresinfo.subjectId = 0; // 假设您想将 subjectId 设置为 0

      // 如果只想设置一个匹配项就退出循环（可选）
      break;
    }
  }
};

//查询讲师数据
const geTeacherList = () => {
  axios.get("/serviceedu/edu-teacher/TeacherList", {}).then((res: any) => {
    console.log(res);
    // 接收总条数
    teacherList.value = res.data.list;
  });
};
// 调用用户初始化查询数据方法
geTeacherList();

//查询所有的一级分类
const getSubjectOne = () => {
  axios.get("/serviceedu/edu-subject/getAllSubject", {}).then((res: any) => {
    console.log(res);
    SubjectOneList.value = res.data.list;
  });
};
// 调用用户初始化查询数据方法
getSubjectOne();
</script>
  
  <style lang="less" scoped>
.demo-form-inline {
  .el-input {
    --el-input-width: 210px;
  }

  .el-select {
    --el-select-width: 210px;
  }
}

.demo-form-inline {
  .el-select {
    --el-select-width: 210px;
  }
}

.el-table {
  margin: 20px 0;
}
</style>